<template>
  <div class="register-container">
    <el-form :model="registerForm" :rules="registerRules" ref="registerFormRef" class="register-form">
      <h3 class="title">用户注册</h3>
      <el-form-item prop="username">
        <el-input
          v-model="registerForm.username"
          placeholder="用户名"
          type="text"
          :prefix-icon="User"
        />
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          v-model="registerForm.password"
          placeholder="密码"
          type="password"
          :prefix-icon="Lock"
          show-password
        />
      </el-form-item>
      <el-form-item prop="confirmPassword">
        <el-input
          v-model="registerForm.confirmPassword"
          placeholder="确认密码"
          type="password"
          :prefix-icon="Lock"
          show-password
        />
      </el-form-item>
      <el-form-item prop="nickname">
        <el-input
          v-model="registerForm.nickname"
          placeholder="昵称"
          :prefix-icon="User"
        />
      </el-form-item>
      <el-form-item prop="captcha">
        <div class="captcha-container">
          <el-input
            v-model="registerForm.captcha"
            placeholder="验证码"
            style="width: 70%"
          />
          <div class="captcha" @click="refreshCaptcha">{{ captcha }}</div>
        </div>
      </el-form-item>
      <el-form-item>
        <el-button
          :loading="loading"
          type="primary"
          style="width:100%"
          @click="handleRegister"
        >
          注册
        </el-button>
      </el-form-item>
      <el-form-item>
        <el-link type="primary" @click="goToLogin">已有账号？去登录</el-link>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { User, Lock } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'

const router = useRouter()
const loading = ref(false)
const captcha = ref('')
const registerFormRef = ref()

const registerForm = reactive({
  username: '',
  password: '',
  confirmPassword: '',
  nickname: '',
  captcha: ''
})

const validateConfirmPassword = (rule, value, callback) => {
  if (value !== registerForm.password) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback()
  }
}

const registerRules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    { validator: validateConfirmPassword, trigger: 'blur' }
  ],
  nickname: [{ required: true, message: '请输入昵称', trigger: 'blur' }],
  captcha: [{ required: true, message: '请输入验证码', trigger: 'blur' }]
}

const refreshCaptcha = async () => {
  try {
    const res = await fetch('http://localhost:8080/api/captcha/get', {
      credentials: 'include'
    })
    const data = await res.json()
    if (data.code === 200) {
      captcha.value = data.data.captcha
    } else {
      ElMessage.error(data.message || '获取验证码失败')
    }
  } catch (error) {
    console.error('获取验证码错误:', error)
    ElMessage.error('获取验证码失败')
  }
}

const handleRegister = async () => {
  await registerFormRef.value.validate()

  loading.value = true
  try {
    const res = await fetch('http://localhost:8080/api/auth/register', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      credentials: 'include',
      body: JSON.stringify(registerForm)
    })
    const data = await res.json()
    if (data.code === 200) {
      ElMessage.success('注册成功')
      router.push('/login')
    } else {
      ElMessage.error(data.message)
      refreshCaptcha()
    }
  } catch (error) {
    ElMessage.error('注册失败')
    refreshCaptcha()
  }
  loading.value = false
}

const goToLogin = () => {
  router.push('/login')
}

onMounted(() => {
  refreshCaptcha()
})
</script>

<style scoped>
.register-container {
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #2d3a4b;
}
.register-form {
  width: 400px;
  padding: 35px;
  border-radius: 5px;
  background: #fff;
}
.title {
  text-align: center;
  margin: 0 0 30px 0;
  color: #333;
}
.captcha-container {
  display: flex;
  align-items: center;
  gap: 10px;
}
.captcha {
  width: 30%;
  height: 40px;
  line-height: 40px;
  text-align: center;
  background: #f0f0f0;
  cursor: pointer;
  user-select: none;
  font-family: monospace;
  font-size: 18px;
  letter-spacing: 4px;
}
</style>
